package com.hp.IO;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestJDBCtxt {

    public static void getCon(){
        Connection con=null;
        PreparedStatement ps=null;

        try {
            //加载jdbc驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //定义连接字符串
            String url="jdbc:mysql://127.0.0.1:3306/mydb6?useUnicode=true&characterEncoding=utf8";
            String user="root";
            String pwd="123";
            //创建数据库连接
            con= DriverManager.getConnection(url,user,pwd);
            //执行sql
            String sql="insert into context(id,novel)values(?,?)";
            ps=con.prepareStatement(sql);
            //给第一个？设为id为1
            ps.setInt(1,1);
            File file=new File("D:\\aa\\c.txt");
            //将文本转为字符输入流
           Reader reader=new InputStreamReader(new FileInputStream(file),"GBK");
           //FileInputStream fis=new FileInputStream(file);
            //            byte[] b=new byte[1024];
//            int cab=0;
//            while ((cab= fis.read(b))>-1){
//                String s=new String(b,0,cab);
//                System.out.println(s);

            //将字符输入流写入数据库
           ps.setCharacterStream(2,reader,(int)file.length());
            int n=ps.executeUpdate();
            if (n>0){
                System.out.println("传入成功");
            }else {
                System.out.println("传入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (ps!=null){
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    if (con!=null){
                        try {
                            con.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }

            }
        }
    }



    public static void main(String[] args) {
        getCon();
    }

}
